// 工具函数文件

// 格式化价格
export const formatPrice = (price) => {
	if (!price && price !== 0) return '0.00'
	return parseFloat(price).toFixed(2)
}

// 格式化数字（添加千分位分隔符）
export const formatNumber = (num) => {
	if (!num && num !== 0) return '0'
	return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 格式化时间
export const formatTime = (timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
	if (!timestamp) return ''
	
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	const seconds = String(date.getSeconds()).padStart(2, '0')
	
	return format
		.replace('YYYY', year)
		.replace('MM', month)
		.replace('DD', day)
		.replace('HH', hours)
		.replace('mm', minutes)
		.replace('ss', seconds)
}

// 获取相对时间
export const getRelativeTime = (timestamp) => {
	if (!timestamp) return ''
	
	const now = new Date().getTime()
	const diff = now - timestamp
	
	const minute = 60 * 1000
	const hour = 60 * minute
	const day = 24 * hour
	const week = 7 * day
	const month = 30 * day
	const year = 365 * day
	
	if (diff < minute) {
		return '刚刚'
	} else if (diff < hour) {
		return Math.floor(diff / minute) + '分钟前'
	} else if (diff < day) {
		return Math.floor(diff / hour) + '小时前'
	} else if (diff < week) {
		return Math.floor(diff / day) + '天前'
	} else if (diff < month) {
		return Math.floor(diff / week) + '周前'
	} else if (diff < year) {
		return Math.floor(diff / month) + '个月前'
	} else {
		return Math.floor(diff / year) + '年前'
	}
}

// 防抖函数
export const debounce = (func, wait) => {
	let timeout
	return function executedFunction(...args) {
		const later = () => {
			clearTimeout(timeout)
			func(...args)
		}
		clearTimeout(timeout)
		timeout = setTimeout(later, wait)
	}
}

// 节流函数
export const throttle = (func, limit) => {
	let inThrottle
	return function() {
		const args = arguments
		const context = this
		if (!inThrottle) {
			func.apply(context, args)
			inThrottle = true
			setTimeout(() => inThrottle = false, limit)
		}
	}
}

// 深拷贝
export const deepClone = (obj) => {
	if (obj === null || typeof obj !== 'object') return obj
	if (obj instanceof Date) return new Date(obj.getTime())
	if (obj instanceof Array) return obj.map(item => deepClone(item))
	if (typeof obj === 'object') {
		const clonedObj = {}
		for (const key in obj) {
			if (obj.hasOwnProperty(key)) {
				clonedObj[key] = deepClone(obj[key])
			}
		}
		return clonedObj
	}
}

// 生成随机ID
export const generateId = () => {
	return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 验证手机号
export const validatePhone = (phone) => {
	const reg = /^1[3-9]\d{9}$/
	return reg.test(phone)
}

// 验证邮箱
export const validateEmail = (email) => {
	const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
	return reg.test(email)
}

// 验证身份证号
export const validateIdCard = (idCard) => {
	const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
	return reg.test(idCard)
}

// 获取文件大小
export const formatFileSize = (bytes) => {
	if (bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取图片信息
export const getImageInfo = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success: resolve,
			fail: reject
		})
	})
}

// 保存图片到相册
export const saveImageToPhotosAlbum = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.saveImageToPhotosAlbum({
			filePath,
			success: resolve,
			fail: reject
		})
	})
}

// 复制到剪贴板
export const setClipboardData = (data) => {
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data,
			success: resolve,
			fail: reject
		})
	})
}

// 获取系统信息
export const getSystemInfo = () => {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: resolve,
			fail: reject
		})
	})
}

// 检查网络状态
export const getNetworkType = () => {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success: resolve,
			fail: reject
		})
	})
}

// 显示加载提示
export const showLoading = (title = '加载中...') => {
	uni.showLoading({
		title,
		mask: true
	})
}

// 隐藏加载提示
export const hideLoading = () => {
	uni.hideLoading()
}

// 显示提示
export const showToast = (title, icon = 'none', duration = 2000) => {
	uni.showToast({
		title,
		icon,
		duration
	})
}

// 显示模态框
export const showModal = (title, content, showCancel = true) => {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title,
			content,
			showCancel,
			success: (res) => {
				if (res.confirm) {
					resolve(true)
				} else {
					resolve(false)
				}
			},
			fail: reject
		})
	})
}

// 显示操作菜单
export const showActionSheet = (itemList) => {
	return new Promise((resolve, reject) => {
		uni.showActionSheet({
			itemList,
			success: (res) => {
				resolve(res.tapIndex)
			},
			fail: reject
		})
	})
}

// 页面跳转
export const navigateTo = (url) => {
	return new Promise((resolve, reject) => {
		uni.navigateTo({
			url,
			success: resolve,
			fail: reject
		})
	})
}

// 重定向页面
export const redirectTo = (url) => {
	return new Promise((resolve, reject) => {
		uni.redirectTo({
			url,
			success: resolve,
			fail: reject
		})
	})
}

// 返回上一页
export const navigateBack = (delta = 1) => {
	return new Promise((resolve, reject) => {
		uni.navigateBack({
			delta,
			success: resolve,
			fail: reject
		})
	})
}

// 重新启动到指定页面
export const reLaunch = (url) => {
	return new Promise((resolve, reject) => {
		uni.reLaunch({
			url,
			success: resolve,
			fail: reject
		})
	})
}

// 切换Tab
export const switchTab = (url) => {
	return new Promise((resolve, reject) => {
		uni.switchTab({
			url,
			success: resolve,
			fail: reject
		})
	})
}

// 获取当前页面路径
export const getCurrentPages = () => {
	return uni.getCurrentPages()
}

// 获取当前页面实例
export const getCurrentPage = () => {
	const pages = getCurrentPages()
	return pages[pages.length - 1]
}

// 获取页面参数
export const getPageParams = () => {
	const page = getCurrentPage()
	return page.options || {}
}

// 设置页面标题
export const setNavigationBarTitle = (title) => {
	uni.setNavigationBarTitle({
		title
	})
}

// 设置TabBar徽标
export const setTabBarBadge = (index, text) => {
	uni.setTabBarBadge({
		index,
		text
	})
}

// 移除TabBar徽标
export const removeTabBarBadge = (index) => {
	uni.removeTabBarBadge({
		index
	})
}

// 隐藏TabBar
export const hideTabBar = (animation = false) => {
	uni.hideTabBar({
		animation
	})
}

// 显示TabBar
export const showTabBar = (animation = false) => {
	uni.showTabBar({
		animation
	})
}

export default {
	formatPrice,
	formatNumber,
	formatTime,
	getRelativeTime,
	debounce,
	throttle,
	deepClone,
	generateId,
	validatePhone,
	validateEmail,
	validateIdCard,
	formatFileSize,
	getImageInfo,
	saveImageToPhotosAlbum,
	setClipboardData,
	getSystemInfo,
	getNetworkType,
	showLoading,
	hideLoading,
	showToast,
	showModal,
	showActionSheet,
	navigateTo,
	redirectTo,
	navigateBack,
	reLaunch,
	switchTab,
	getCurrentPages,
	getCurrentPage,
	getPageParams,
	setNavigationBarTitle,
	setTabBarBadge,
	removeTabBarBadge,
	hideTabBar,
	showTabBar
} 